package com.huangliusong.spring.servlet.AsyncServlet;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 异步的servlet
 * @author huangliusong
 * @since 2018/10/6
 * {@link WebServlet}
 */
@WebServlet(asyncSupported = true,//active async
        name = "asyncServlet",
        urlPatterns = "/async-servlet"
)
public class AsyncServlet extends HttpServlet {

    //覆盖service
    @Override
    public void service(HttpServletRequest request, HttpServletResponse response)throws IOException,ServletException {

        //判断是否支持异步
        if (request.isAsyncSupported()){
            //create asyncContext
            AsyncContext asyncContext=request.startAsync();
            asyncContext.addListener(new AsyncListener() {
                @Override
                public void onComplete(AsyncEvent asyncEvent) throws IOException {
                    println("执行完成");
                }

                @Override
                public void onTimeout(AsyncEvent asyncEvent) throws IOException {
                    HttpServletResponse servletResponse=(HttpServletResponse)asyncEvent.getSuppliedResponse();
                    servletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                    println("执行超时");
                }

                @Override
                public void onError(AsyncEvent asyncEvent) throws IOException {
                    println("执行错误");
                }

                @Override
                public void onStartAsync(AsyncEvent asyncEvent) throws IOException {
                    println("开始执行");
                }
            });

           ServletResponse servletResponse= asyncContext.getResponse();
           //设置相应的媒体类型
           servletResponse.setContentType("text/plain;charset=UTF-8");
           PrintWriter writer=servletResponse.getWriter();
           writer.print("hi i m hls");
            writer.flush();


        }
    }

    private static void println(Object object){
        String threadName=Thread.currentThread().getName();
        System.err.println("AsyncServlet线程名称 "+threadName+" "+object);
    }
}
